<script setup lang="ts">
import { addManageAPI, deleteManageAPI, editManageAPI, getDropListAPI, getManageDataAPI } from '@/apis/rodManage';
import { PoleType } from '@/enums/rodManage';
import type { AddManageParamsType,  DropItemType,  GetManageParamsType, ManageItemType } from '@/types/rodManage';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { ref } from 'vue';

// 获取列表所需参数
const getManageParams = ref<GetManageParamsType>({
  page: 1, // 页码
  pageSize: 5, // 每页条数
  poleName: undefined, // 一体杆名称
  poleNumber: undefined, // 一体杆编号
  poleStatus: undefined // 运行状态 0:正常,1:异常
})

// 获取列表数据 --------------
const manageTotal = ref<number>(0) // 总条数
const manageList = ref<ManageItemType[]>() // 列表数据
const getManageData = async () => {
  const res = await getManageDataAPI(getManageParams.value)
  manageTotal.value = res.data.total
  manageList.value = res.data.rows
}
getManageData()

// 一体杆类型
const poleType = (row: ManageItemType) => {
  return row.poleType === PoleType.Entrance ? '入口' : '出口'
}
// 运行状态
const poleStatus = (row: ManageItemType) => {
  return row.poleStatus === 0 ? '正常' : '异常'
}

// 弹窗 添加/编辑 ---------------------
const dialogVisible = ref(false) // 弹窗控制
const formRef = ref<FormInstance>() // 表单实例
const dialogType = ref<'add' | 'edit'>('add') // 弹窗类型 add添加 edit编辑
const parkId = ref<number>(0) // 弹窗编辑时，需要传入的id
// 打开弹窗
const openDialog = async (row?: ManageItemType) => {
  await getDropList() // 获取下拉列表
  if (row) {
    // 编辑
    dialogType.value = 'edit'

    // 回显数据
    addManageParams.value = {
      areaId: row.areaId, // 关联区域ID
      poleIp: row.poleIp, // 一体杆IP
      poleName: row.poleName, // 一体杆名称
      poleNumber: row.poleNumber, // 一体杆编号
      poleType: row.poleType // 一体杆类型entrance:入口,export:出口
    }
    parkId.value = row.id
  } else {
    // 添加
    dialogType.value = 'add'
  }

  dialogVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false

  formRef.value?.resetFields() // 重置表单
  addManageParams.value = {
    areaId: undefined, // 关联区域ID
    poleIp: '', // 一体杆IP
    poleName: '', // 一体杆名称
    poleNumber: '', // 一体杆编号
    poleType: undefined // 一体杆类型entrance:入口,export:出口
  }
  parkId.value = 0
}

// 操作一体嘎所需类型
const addManageParams = ref<AddManageParamsType>({
  areaId: undefined, // 关联区域ID
  poleIp: '', // 一体杆IP
  poleName: '', // 一体杆名称
  poleNumber: '', // 一体杆编号
  poleType: undefined // 一体杆类型entrance:入口,export:出口
})

// 表单规则
const formRules = ref<FormRules<AddManageParamsType>>({
  areaId: [
    { required: true, message: '请选择关联区域', trigger: 'change' }
  ],
  poleIp: [
    { required: true, message: '请输入一体杆IP', trigger: 'blur' },
    // ip正则校验
    { pattern: /^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(?::(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?$/, message: '必须为IP地址', trigger: 'blur' },
  ],
  poleName: [
    { required: true, message: '请输入一体杆名称', trigger: 'blur' }
  ],
  poleNumber: [
    { required: true, message: '请输入一体杆编号', trigger: 'blur' }
  ],
  poleType: [
    { required: true, message: '请选择一体杆类型', trigger: 'change' }
  ]
})

// 获取关联区域下拉列表
const dropList = ref<DropItemType[]>([])
const getDropList = async () => {
  const res = await getDropListAPI()
  dropList.value = res.data
}

// 添加/编辑提交
const loadingFlag = ref(false)
const submitDialogForm = async () => {
  await formRef.value?.validate()
  loadingFlag.value = true
  
  try {
    if (dialogType.value === 'add') {
      // 添加
      await addManageAPI(addManageParams.value)
      ElMessage.success('添加成功')
    } else if (dialogType.value === 'edit') {
      // 编辑
      const res = await editManageAPI({
        ...addManageParams.value,
        id: parkId.value
      })
      if (res.code === 10000) {
        ElMessage.success('编辑成功')
      } else {
        ElMessage.error(res.msg)
      }
    }
  } finally {
    loadingFlag.value = false
  }

  getManageData() // 刷新表格数据
  closeDialog() // 关闭弹窗
}

// 删除一体杆
const deleteManage = async (ids: number[]) => {
  if (ids.length === 0) {
    ElMessage.warning('请选择要删除的一体杆')
    return
  }

  await ElMessageBox.confirm('确定删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })

  const res = await deleteManageAPI(ids)
  // 判断是否是演示数据
  if (res.code === 10000) {
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.msg)
  }
  getManageData() // 刷新表格数据
}

// 统计表格选中的数据
const selectionManageList = ref<ManageItemType[]>([])
const onSelectionChange = (val: ManageItemType[]) => {
  selectionManageList.value = val
}

// 批量删除
const deleteManageList = async () => {
  const ids = selectionManageList.value.map(item => item.id)
  deleteManage(ids)
}

</script>

<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">一体嘎名称：</span>
      <el-input v-model="getManageParams.poleName" @clear="getManageData()" placeholder="请输入一体杆名称" clearable class="search-main" />
      <span class="search-label">一体嘎编号：</span>
      <el-input v-model="getManageParams.poleNumber" @clear="getManageData()" placeholder="请输入一体嘎编号" clearable class="search-main" />
      <span class="search-label">运行状态状态：</span>
      <el-select v-model="getManageParams.poleStatus" @clear="getManageData()" placeholder="请选择运行状态" clearable style="width: 240px">
        <el-option label="正常" value="0" />
        <el-option label="异常" value="1" />
      </el-select>
      <el-button type="primary" class="search-btn" @click="getManageData()">查询</el-button>
    </div>
    <!-- 新增删除 -->
    <div class="create-container">
      <div class="left">
        <el-button type="primary" @click="openDialog()" v-permission="'pole:info:add_edit'">添加一体杆</el-button>
        <el-button @click="deleteManageList()" v-permission="'pole:info:remove'">批量删除</el-button>
      </div>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="manageList" @selection-change="onSelectionChange">
        <el-table-column type="selection" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="一体嘎名称" prop="poleName" />
        <el-table-column label="一体杆编号" prop="poleNumber" />
        <el-table-column label="一体杆IP" prop="poleIp" />
        <el-table-column label="安装区域" prop="areaName" />
        <el-table-column label="一体嘎类型" prop="poleType" :formatter="poleType" />
        <el-table-column label="运行状态" prop="poleStatus" :formatter="poleStatus" />
        <el-table-column label="操作" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="openDialog(row)" v-permission="'pole:info:add_edit'">编辑</el-button>
            <el-button size="small" type="primary" link @click="deleteManage([row.id])" v-permission="'pole:info:remove'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-container">
      <el-pagination 
        layout="total, sizes, prev, pager, next"
        :total="manageTotal"
        :page-sizes="[2,5,10,20]"
        v-model:current-page="getManageParams.page"
        v-model:page-size="getManageParams.pageSize"
        @change="getManageData"
      />
    </div>
    <!-- 弹窗 -->
     <el-dialog :title="dialogType === 'add' ? '添加一体杆' : '编辑一体杆'" width="580px" v-model="dialogVisible" @close="closeDialog()">
      <div class="form-container">
        <!-- 表单区域 -->
        <el-form ref="formRef" label-position="top" :model="addManageParams" :rules="formRules">
          <el-form-item label="一体杆名称" prop="poleName">
            <el-input placeholder="请输入一体杆名称" v-model="addManageParams.poleName"></el-input>
          </el-form-item>
          <el-form-item label="一体杆编号" prop="poleNumber">
            <el-input :disabled="dialogType === 'edit'" placeholder="请输入一体杆编号" v-model="addManageParams.poleNumber"></el-input>
          </el-form-item>
          <el-form-item label="一体嘎IP" prop="poleIp">
            <el-input placeholder="请输入一体杆IP" v-model="addManageParams.poleIp"></el-input>
          </el-form-item>
          <el-form-item label="关联区域" prop="areaId">
            <el-select v-model="addManageParams.areaId" placeholder="请选择关联区域">
              <el-option
                v-for="item in dropList"
                :key="item.areaId"
                :label="item.areaName"
                :value="item.areaId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="一体杆类型" prop="poleType">
            <el-select v-model="addManageParams.poleType" placeholder="请选择一体杆类型" clearable>
              <el-option label="入口" :value="PoleType.Entrance"></el-option>
              <el-option label="出口" :value="PoleType.Export"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
       <template #footer>
         <div class="dialog-footer">
            <el-button @click="closeDialog">取 消</el-button>
            <el-button type="primary" @click="submitDialogForm()" :loading="loadingFlag">确 定</el-button>
         </div>
       </template>
     </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-main {
    width: 220px;
    margin-right: 10px;
  }

  .search-btn {
    margin-left: 20px;
  }
}

.create-container {
  display: flex;
  justify-content: space-between;
  margin: 20px 0px;
  .right {
    height: 35px;
    line-height: 35px;
    padding: 0px 10px;
    background-color: #e6f7ff;
    border: 1px solid #abdfff;
    border-radius: 5px;
    font-size: 13px;
    display: flex;
    align-items: center;
  }
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
